package cn.edu.nju.ws.sview.servlets;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;

import com.jspsmart.upload.SmartUpload;

/**
 * Servlet implementation class UploadImage
 */
@WebServlet("/UploadImage")
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImage() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		SmartUpload mySmartUpload =new SmartUpload();
		String type="success";
		long file_size_max=4000000;
		String url="uploadfile/images/";    
		mySmartUpload.initialize(this.getServletConfig(), request, response);
//		mySmartUpload.initialize(this.getServletConfig(),request,response);
		boolean flag = false;
		try {
			mySmartUpload.setAllowedFilesList("jpg,gif,png");
			mySmartUpload.upload();
		} catch (Exception e){
			type="wrong format";
			e.printStackTrace();
			flag = true;
		}
		if(!flag){
		try{
		   com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
		   String ext= myFile.getFileExt();   
		   int file_size=myFile.getSize();    
		   String saveurl="";
		   if(file_size<file_size_max){
		     String filename = String.valueOf(System.currentTimeMillis()); 
		     saveurl=request.getRealPath("/")+url;
		     saveurl+=filename+"."+ext;  
		     File file = new File(request.getRealPath("/")+url);
		     if(!file.exists())
		    	 file.mkdirs();
		     myFile.saveAs(saveurl,mySmartUpload.SAVE_AUTO);
		    }
		   else{
			   type="too large";
		   }
		}catch (Exception e){
		   type="some error" ;
		   e.printStackTrace();
		}
		}
		JSONObject result = new JSONObject();
		result.put("type", type) ;
		response.getWriter().print(result) ;
	}
}
